// ducks模式代码

// 常量 命名空间 
export const types = {
  CHANGE_FROM_TO: 'CHANGE_FROM_TO',
  GET_CITY_DATA: 'GET_CITY_DATA',
  INIT_CITY_DATA: 'INIT_CITY_DATA',
  SELECT_CITY: 'select_city',
  SWITCH_FLAG: 'switch_flag'
}

// action
export const actions = {
  changeFromTo(city: any) {
    return {
      type: types.CHANGE_FROM_TO,
      city
    }
  },
  getCityData() { // redux-thunk

    return (dispatch: any) => {
      fetch(`/rest/cities?_` + Date.now())
        .then(res => res.json())
        .then(data => {
          const action = (this as any).initCityData(data);
          // console.log("action:", action)
          dispatch(action)
          // dispatch((this as any).initCityData())
        })
    }
  },
  initCityData(data: any) {
    return {
      type: types.INIT_CITY_DATA,
      data
    }
  },
  // 城市选择的action
  selectCity({ from, to, dir }: { from: string, to: string, dir: string }) {
    return {
      type: types.SELECT_CITY,
      data: { from, to, dir }
    }
  },
  setSwitchFlag(flag: boolean) {
    return {
      type: types.SWITCH_FLAG,
      flag
    }
  }
}

// reducer
const defaultState = {
  from: '北京',
  to: '上海',
  cityList: [],
  hotCities: [],
  switchFlag: false
}
export default (state = defaultState, action: any) => {
  switch (action.type) {
    case types.CHANGE_FROM_TO:
      // reducer中放置判断逻辑
      state.from = action.city.to
      state.to = action.city.from
      return { ...state }
    case types.INIT_CITY_DATA:
      // console.log("ACtion: ", action)
      state.cityList = action.data.cityList
      state.hotCities = action.data.hotCities
      return { ...state }
    // 城市选择
    case types.SELECT_CITY:
      console.log("action:", action)
      state.from = action.data.from;
      state.to = action.data.to
      return { ...state }
    case types.SWITCH_FLAG:
      state.switchFlag = action.flag
      return { ...state }

    default:
      return { ...state }

  }

  return { ...state }
}


